package com.mrs.gauss.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.validator.constraints.Length;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

@Log4j2
public class HdfsSummary {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static String printResponse(CloseableHttpResponse httpResponse) throws Exception {
        HttpEntity entity = httpResponse.getEntity();
        String entiryString = "";
        if (entity != null) {
            entiryString = EntityUtils.toString(entity);

        }
        EntityUtils.consume(entity);
        return entiryString;
    }


    public  List<Map> getHdfsSummary() throws Exception
    {
        LocalDateTime currentEndTime = LocalDateTime.now();
        String userFilePath = "./conf/UserInfo.properties";
        InputStream userInfo = null;
        File file = new File(userFilePath);
        if (!file.exists()) {
            log.error("The user info file doesn't exist.");
        }
        userInfo = new BufferedInputStream(new FileInputStream(file));
        ResourceBundle resourceBundle = new PropertyResourceBundle(userInfo);
        String username = resourceBundle.getString("userName");
        String password = resourceBundle.getString("password");
        String ipAddr = resourceBundle.getString("webUrl");
        String url;
        url = ipAddr + "/api/v1/clusters/2/summary";
        HttpGet httpGet = new HttpGet(url);
        String authStr = username + ":" + password;
        String encoding = DatatypeConverter.printBase64Binary(authStr.getBytes("UTF-8"));
        httpGet.setHeader("Authorization", "Basic " + encoding);
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        List<Map> summary = jsonToMaps(printResponse(httpResponse));
        return summary;
    }


    public static List<Map> jsonToMaps(String json) throws IOException {
        Map map = OBJECT_MAPPER.readValue(json, Map.class);
        return (List) (map.get("properties"));
    }
}
